package com.guaoran.source.spring.framework.context.support;

import com.guaoran.source.spring.framework.beans.BeanDefinition;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * @author : 孤傲然
 * @Description :
 * @date :2018/6/19 18:51
 */
public class BeanDefinitionReader {
    private Properties contextConfig = new Properties();
    //用来存储class文件
    private List<String> registyBeanClasses = new ArrayList<String>();
    //在配置文件中，用来获取自动扫描的包名的key
    private static final String SCAN_PACKAGE = "scanPackage";

    /**
     * 定位、查找、解析配置文件
     * 将web.xml中的servlet 中配置的配置文件进行加载到文件中（param-value）
     *
     * @param configLocations
     */
    public BeanDefinitionReader(String... configLocations) {
        //定位配置文件，
        InputStream is = this.getClass().getClassLoader().getResourceAsStream(configLocations[0].replace("classpath:", ""));
        try {
            contextConfig.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //扫描加载该目录下的所有class文件
        doScanner(contextConfig.getProperty(SCAN_PACKAGE));
    }

    /**
     * 扫描目录下面的所有文件和递归扫描子包文件
     *
     * @param packageName
     */
    private void doScanner(String packageName) {
        //将文件中的com.guaoran.source转换成具体的文件路径com/guaoran/source 加载到registyBeanClasses中
        URL url = this.getClass().getClassLoader().getResource("/" + packageName.replaceAll("\\.", "/"));
        File classDir = new File(url.getFile());
        if (classDir != null) {
            for (File file : classDir.listFiles()) {
                if (file.isDirectory()) {
                    doScanner(packageName + "." + file.getName());
                } else {
                    registyBeanClasses.add(packageName + "." + file.getName().replace(".class", ""));
                }
            }
        }
    }


    public List<String> loadBeanDeifinitions() {
        return registyBeanClasses;

    }

    /**
     * 注册bean
     * 根据className进行注册，封装到BeanDefinition中
     *
     * @param className
     * @return
     */
    public BeanDefinition registerBean(String className) {
        if (this.registyBeanClasses.contains(className)) {
            BeanDefinition beanDefinition = new BeanDefinition();
            beanDefinition.setBeanClassName(className);
            beanDefinition.setFactoryBeanName(lowerFirstCase(className.substring(className.lastIndexOf(".") + 1)));
            beanDefinition.setSocpe("singleton");
            return beanDefinition;
        }
        return null;
    }

    private String lowerFirstCase(String str) {
        char[] chars = str.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }

    public Properties getContextConfig() {
        return contextConfig;
    }
}
